package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference(version = "1.0.0")
    private UserService userService;


    @GetMapping("/getUser")
    public Result getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String username = principal.getUsername();
        return Result.success(username);
    }

    @PostMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){
        if (queryPageBean.getQueryString() != null && queryPageBean.getCurrentPage() != 1) {
            queryPageBean.setCurrentPage(1);
        }
        return userService.findPage(queryPageBean);
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user){
        return userService.save(user);
    }

    @PostMapping("update")
    public Result update(@RequestBody User user){
        return userService.update(user);
    }

    @GetMapping("delete")
    public Result delete(Integer id){
        return userService.delete(id);
    }

    @PostMapping("findAll")
    public Result findAll(){
        return userService.findAll();
    }

    @GetMapping("findById")
    public Result findById(Integer id){
        return userService.findById(id);
    }

}
